<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage} from "element-plus";
import router from "@/router";
import axios from "axios";
import qs from "qs";

const appointment = ref({});
const department = ref('');
const doctor = ref('');

const user = ref({});
let oldUser = ref({});
const userToken = ref(localStorage.getItem('user-token') ?
    JSON.parse(localStorage.getItem('user-token')) : null);
const userId = ref(localStorage.getItem('user-id') ?
    JSON.parse(localStorage.getItem('user-id')) : null);

const c1 = [{value: '入职体检'}, {value: '普通体检'}, {value: '就诊挂号'}, {value: '其他'},];
const c2 = [{value: '普通号'}, {value: '专家号'}, {value: '名医号'}];
const c3 = [{value: '男'}, {value: '女'}];

let update = true;

onMounted(() => {
  if (userToken.value == null) {
    ElMessage.error("请先登录!");
    router.push('/patient/login');
    return;
  }
  axios.defaults.headers.common['Authorization'] = userToken.value;

  axios.get(BASE_URL + "/v1/users/select/" + userId.value).then((response) => {
    if (response.data.code === 20000) {
      user.value = response.data.data;
    } else ElMessage.error(response.data.message)
  })
  axios.get(BASE_URL + "/v1/users/select/" + userId.value).then((response) => {
    if (response.data.code === 20000) {
      oldUser.value = response.data.data;
    } else ElMessage.error(response.data.message)
  })
  axios.get(BASE_URL + "/v1/doctors/type").then((response) => {
    if (response.data.code === 20000) {
      doctor.value = response.data.data;
    } else ElMessage.error(response.data.message)
  })
  axios.get(BASE_URL + "/v1/department/select-level").then((response) => {
    if (response.data.code === 20000) {
      department.value = response.data.data;
    } else ElMessage.error(response.data.message)
  })
})

const changeDepartment = (id) => {
  axios.get(BASE_URL + "/v1/department/selectDoctor/" + id).then((response) => {
    if (response.data.code === 20000) {
      doctor.value = response.data.data;
      appointment.value.doctorId = '';
    } else ElMessage.error(response.data.message)
  })
}

const save = () => {
  if (appointment.value.project == null) {
    ElMessage.error("请选择预约的项目!")
    return;
  }
  if (appointment.value.type == null) {
    ElMessage.error("请选择预约类型!")
    return;
  }
  if (user.value.gender == null) {
    ElMessage.error("请选择您的性别!")
    return;
  }
  if (user.value.mobile == null || user.value.mobile === '') {
    ElMessage.error("请输入您的手机号!")
    return;
  }
  if (appointment.value.departmentId == null && doctors.value.departmentName == null) {
    ElMessage.error("请选择想要预约的科室!")
    return;
  }
  if (doctors.value.departmentId!=null) {
    appointment.value.departmentId = doctors.value.departmentId;
  }
  if ((appointment.value.doctorId == null || appointment.value.doctorId === '')
      && doctors.value.doctorName == null) {
    ElMessage.error("请选择想要预约的医生!")
    return;
  }
  if (doctors.value.id!=null) {
    appointment.value.doctorId = doctors.value.id;
  }
  if (appointment.value.createDate == null) {
    ElMessage.error("请选择想要预约的日期!")
    return;
  }
  if (appointment.value.createTime == null) {
    ElMessage.error("请选择想要预约的时间段!")
    return;
  }
  if (oldUser.value.gender !== user.value.gender || oldUser.value.mobile !== user.value.mobile) {
    let userData = qs.stringify(user.value);
    axios.post(BASE_URL + "/v1/users/updateUser", userData).then((response) => {
      if (response.data.code === 20000) {
        ElMessage.success("修改个人信息成功!")
      } else {
        ElMessage.warning(response.data.message)
        update = false;
      }
    })
    if (!update) {
      return;
    }
  }
  const date = new Date(appointment.value.createDate);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = appointment.value.createTime.substring(0, 2);
  const minutes = appointment.value.createTime.substring(3);
  appointment.value.createDate = `${year}-${month}-${day} ${hours}:${minutes}:00`;
  appointment.value.patientId = user.value.patientId;
  let data = qs.stringify(appointment.value);
  axios.post(BASE_URL + "/v1/appointments/insert", data).then((response) => {
    if (response.data.code === 20000) {
      ElMessage.success("新建预约成功!")
      router.push('/patient/appointment')
    } else ElMessage.error(response.data.message)
  })
}

const doctors = ref({});
onMounted(() => {
  const urlParams = new URLSearchParams(window.location.search);
  const id = urlParams.get('id');
  if (id != null) {
    axios.get(BASE_URL + "/v1/doctors/select/" + id).then((response) => {
      if (response.data.code === 20000) {
        doctors.value = response.data.data;
      } else ElMessage.error(response.data.message)
    })
  }
})
</script>

<template>
  <el-row>
    <div style="float: left;font-size: 25px;color: gray;font-weight: bold">新建预约</div>
  </el-row>
  <el-divider border-style="solid" style="margin: 10px 0"/>
  <el-card style="margin: 0 auto;width:1000px">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="预约号 :" label-width="100">
          <el-input v-model="appointment.appointment" placeholder="根据规则自动生成" class="formInput" disabled/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="姓名 :" :required="true" label-width="120">
          <el-input v-model="user.nickname" class="formInput" disabled/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="预约项目 :" :required="true" label-width="100">
          <el-select v-model="appointment.project" placeholder="请选择" class="formInput">
            <el-option v-for="item in c1" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="预约类型 :" :required="true" label-width="120">
          <el-select v-model="appointment.type" placeholder="请选择" class="formInput">
            <el-option v-for="item in c2" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="性别 :" :required="true" label-width="100">
          <el-select v-model="user.gender" class="formInput"
                     placeholder="请选择" :disabled="oldUser.gender!=null">
            <el-option v-for="item in c3" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="手机号码 :" :required="true" label-width="120">
          <el-input v-model="user.mobile" class="formInput" :disabled="oldUser.mobile!=null"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="科室 :" label-width="100" :required="true">
          <el-select v-if="doctors.id==null" v-model="appointment.departmentId" class="formInput"
                     placeholder="请选择" @change="changeDepartment(appointment.departmentId)">
            <el-option v-for="d in department" :label="d.name" :value="d.id"/>
          </el-select>
          <el-select v-else v-model="doctors.departmentName" class="formInput" disabled/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="就诊卡号 :" label-width="120">
          <el-input v-model="user.number" class="formInput" disabled/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="预约医生 :" label-width="100" :required="true">
          <el-select v-if="doctors.id==null" v-model="appointment.doctorId" placeholder="请选择" class="formInput">
            <el-option v-for="d in doctor" :label="d.nickname" :value="d.id"/>
          </el-select>
          <el-select v-else v-model="doctors.doctorName" class="formInput" disabled/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="预约时间 :" label-width="120" :required="true">
          <el-date-picker v-model="appointment.createDate" type="date"
                          placeholder="请选择" format="YYYY-MM-DD"/>
          <span>&nbsp; - &nbsp;</span>
          <el-time-select v-model="appointment.createTime" placeholder="请选择"
                          start="08:00"
                          step="00:30"
                          end="18:00"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-form-item label="备注 :" label-width="100">
        <el-input v-model="appointment.remark" type="textarea" :rows="10" style="width: 805px;"/>
      </el-form-item>
    </el-row>
    <el-row>
      <div style="margin: 0 auto">
        <el-button style="background-color: #409EFF;color: white;width: 160px" @click="save">提 &nbsp; &nbsp; 交
        </el-button>
      </div>
    </el-row>
  </el-card>
</template>

<style scoped>
.el-select {
  width: 140px;
}

/deep/ .el-date-editor {
  --el-date-editor-width: 140px;
}

.formInput {
  width: 300px;
  height: 35px;
}
</style>